import { axios } from "apis";
import {
  LoginParamsType,
  CreateUserType,
  CreateUserResponse,
  LoginByMobileParamsType,
} from "apis/module/sys";
import { Buffer } from "buffer";
import qs from "qs";
import { API } from "types";
import { config, OAUTH_URL } from "types/module/config";

const baseAuthString = () => {
  const str = Buffer.from(
    `${config.client_id}:${config.client_secret}`,
  ).toString("base64");
  return `Basic ${str}`;
};

// const headers = {
//   'Content-Type': 'application/json',
// };
// {"error":"unauthorized","error_description":"UserDetailsService returned null, which is an interface contract violation","code":"unauthorized","exception":"用户名或密码错误","serial":"authserver_aaa3f20b124542d4881a6bb260cd51e8"}
export function apiUserLogin(
  data: LoginParamsType,
): Promise<API.ApiResponse<API.TokenType>> {
  // eslint-disable-next-line no-param-reassign
  data.grant_type = "password";
  return axios.request({
    method: "POST",
    url: OAUTH_URL,
    data: qs.stringify(data),
    headers: {
      // ...headers,
      // 配合 oauth，client_id 加密信息
      // client_id = web, pwd = 123
      Authorization: baseAuthString(), // "Basic d2ViOjEyMw==",
    },
  });
}

export function apiGetUser(): Promise<API.ApiResponse<API.UserType>> {
  return axios.request({
    method: "GET",
    url: "/manager/medical-staff/staff-info-His",
  });
}

export function apiGetMenuData(): Promise<
  API.ApiResponse<[API.MenuDataItemType]>
> {
  return axios.request({
    method: "GET",
    url: "/manager/user/menudata",
  });
}

// TODO 以下没改
export function apiCreateUser(data: CreateUserType) {
  return axios.request<CreateUserResponse>({
    method: "POST",
    url: "/user/register",
    data,
  });
}

export function apiUserLoginByMobile(data: LoginByMobileParamsType) {
  // eslint-disable-next-line no-param-reassign
  data.grant_type = "password";
  return axios.request<API.TokenType>({
    method: "POST",
    url: OAUTH_URL,
    data: qs.stringify(data),
    // data,
    headers: {
      Authorization: baseAuthString(),
    },
  });
}

interface MobileLoginiData {
  mobile: string;
}

export function apiGetVerifyCode(data: MobileLoginiData) {
  return axios.request({
    method: "POST",
    url: "/manager/user/code",
    data: qs.stringify(data),
  });
}

export function apiUpdateUserPwd(data: string) {
  return axios.request({
    method: "POST",
    url: "/user/code",
    data,
  });
}
